package InternetCode.Socket.Exa10;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 通过Socket传输对象数据
 */
public class ClientSocketFrame {

    private ObjectOutputStream writer;
    private ObjectInputStream reader;
    private Socket socket;
    private Scanner scanner;


    private void connect() {
        System.out.println("尝试连接......\n");
        try {
            // 连接服务器获得套接字
            socket = new Socket("127.0.0.1", 1978);
            while (true) {
                writer = new ObjectOutputStream(socket.getOutputStream());
                reader = new ObjectInputStream(socket.getInputStream()); // 实例化BufferedReader对象
                getServerInfo();
            }
        } catch (Exception e) {
            e.printStackTrace(); // 输出异常信息
        }
    }

    /**
     * 监听服务器发送来的对象数据
     */
    private void getServerInfo() {
        try {
            while (true) { // 如果套接字是连接状态
                if (reader != null) {
                    Student student=(Student) reader.readObject();
                    if (student != null)
                        System.out.println("接收到服务器发送的信息：学生编号" +student.getId() +"学生姓名："+student.getName()+ "\n"); // 获得客户端信息
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();// 关闭流
                }
                if (socket != null) {
                    socket.close(); // 关闭套接字
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 向服务器发送消息方法
     */
    private void sendInfoToServer(){
        while(true){
            scanner=new Scanner(System.in);
            System.out.println("请输入要发送的消息:");
            String id=scanner.nextLine();
            String name=scanner.nextLine();
            if(id.equals("quit")){
                break;
            }
            try{
                writer.writeObject(new Student(id,name));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) { // 主方法
        ClientSocketFrame client = new ClientSocketFrame(); // 创建本例对象
        //此线程用于监听接收消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.connect(); // 调用连接方法
            }
        }).start();
        //此线程用发送消息给服务器
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.sendInfoToServer(); // 调用连接方法
            }
        }).start();
    }

}
